package com.hikvision.rpq.sblearn.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import sun.dc.pr.PRError;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author renpeiqian
 * @date 2021/9/7 15:59
 * @since
 */
@Configuration
public class ThreadPoolConfig {


    /**
     * 使用@ConfigurationProperties注解，可以将thread.pool开头的参数直接赋值到ThreadPoolProperties类的同名参数中，这样省去了像@Value注解那样一个个手动去对应的过程。
     * 这种方式显然要方便很多，只需编写xxxProperties类，Spring会自动装配参数。此外，不同系列的参数可以定义不同的xxxProperties类，也便于管理，推荐优先使用这种方式。
     */

    @Autowired
    private ThreadPoolProperties threadPoolProperties;


    @Bean
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
